<template>
  <div class="post-detail">
    <!-- 帖子头部 - 添加安全检查 -->
    <div class="post-header" v-if="post?.author">
      <div class="user-info">
        <el-avatar :size="48" :src="post.author.avatar || ''" />
        <div class="user-details">
          <span class="user-name">{{ post.author.name || '未知用户' }}</span>
          <el-tag 
            :type="(post.author.type || 'buyer') === 'farmer' ? 'success' : 'info'"
            size="small"
          >
            {{ (post.author.type || 'buyer') === 'farmer' ? '农夫' : '买家' }}
          </el-tag>
          <div class="user-uid" v-if="post.author.id">UID: {{ post.author.id }}</div>
        </div>
      </div>
      <span class="post-time">{{ formatDate(post.createTime) }}</span>
    </div>

    <!-- 帖子内容 -->
    <div class="post-content" v-if="post">
      <p class="post-text">{{ post.content }}</p>

      <!-- 关键词 -->
      <div v-if="post.keywords && post.keywords.length" class="post-keywords">
        <el-tag 
          v-for="(keyword, index) in post.keywords" 
          :key="index"
          type="info" 
          size="small"
          class="keyword-tag"
        >
          #{{ keyword }}
        </el-tag>
      </div>

      <!-- 图片 -->
      <div v-if="post.images && post.images.length" class="post-images">
        <div 
          v-for="(image, index) in post.images" 
          :key="index"
          class="post-image"
          :style="{ backgroundImage: `url(${image})` }"
          @click="previewImage(image)"
        >
          <div class="image-overlay">
            <el-icon><ZoomIn /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 帖子统计 -->
    <div class="post-stats-detail" v-if="post">
      <div class="stats-grid">
        <div class="stat-item">
          <el-icon color="#f59e0b"><Star /></el-icon>
          <span class="stat-label">点赞</span>
          <span class="stat-value">{{ post.likes || 0 }}</span>
        </div>
        <div class="stat-item">
          <el-icon color="#6b7280"><ChatDotRound /></el-icon>
          <span class="stat-label">评论</span>
          <span class="stat-value">{{ post.comments?.length || 0 }}</span>
        </div>
        <div class="stat-item">
          <el-icon color="#ef4444"><CircleClose /></el-icon>
          <span class="stat-label">点踩</span>
          <span class="stat-value">{{ post.dislikes || 0 }}</span>
        </div>
        <div class="stat-item">
          <el-icon color="#10b981"><TrendCharts /></el-icon>
          <span class="stat-label">热度</span>
          <span class="stat-value">{{ post.hotScore || '--' }}</span>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="post-actions" v-if="post">
      <div class="action-group">
        <el-button 
          :type="post.userAction === 'like' ? 'primary' : 'default'"
          @click="handleLike"
          :class="{ 'active': post.userAction === 'like' }"
        >
          <el-icon><Star /></el-icon>
          点赞 {{ post.likes || 0 }}
        </el-button>
        
        <el-button 
          :type="post.userAction === 'dislike' ? 'danger' : 'default'"
          @click="handleDislike"
          :class="{ 'active': post.userAction === 'dislike' }"
        >
          <el-icon><CircleClose /></el-icon>
          点踩 {{ post.dislikes || 0 }}
        </el-button>
        
        <el-button 
          type="default"
          @click="toggleComments"
          :class="{ 'active': showComments }"
        >
          <el-icon><ChatDotRound /></el-icon>
          评论 {{ post.comments?.length || 0 }}
        </el-button>

        <!-- 举报按钮 -->
        <el-button 
          type="danger" 
          plain
          @click="handleReport"
          v-if="!isOwnPost && post.author"
        >
          <el-icon><Warning /></el-icon>
          举报
        </el-button>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section" v-if="showComments && post">
      <!-- 评论列表 -->
      <div class="comments-list" v-if="post.comments && post.comments.length > 0">
        <div 
          v-for="comment in post.comments" 
          :key="comment.id"
          class="comment-item"
        >
          <div class="comment-header">
            <el-avatar :size="32" :src="comment.author?.avatar || ''" />
            <div class="comment-author">
              <span class="author-name">{{ comment.author?.name || '未知用户' }}</span>
              <span class="comment-time">{{ formatDate(comment.createTime || comment.time) }}</span>
              <span class="comment-uid" v-if="comment.author?.id">UID: {{ comment.author.id }}</span>
            </div>
            <!-- 评论操作 -->
            <div class="comment-actions" v-if="comment.author && !isCurrentUser(comment.author.id)">
              <el-button 
                size="small" 
                type="text"
                @click="handleReply(comment)"
              >
                <el-icon><ChatDotRound /></el-icon>
                回复
              </el-button>
            </div>
          </div>
          <p class="comment-content">{{ comment.content }}</p>
          
          <!-- 回复列表 -->
          <div v-if="comment.replies && comment.replies.length" class="replies-list">
            <div 
              v-for="reply in comment.replies" 
              :key="reply.id"
              class="reply-item"
            >
              <div class="reply-header">
                <el-avatar :size="28" :src="reply.author?.avatar || ''" />
                <div class="reply-author">
                  <span class="author-name">{{ reply.author?.name || '未知用户' }}</span>
                  <span class="reply-time">{{ formatDate(reply.createTime || reply.time) }}</span>
                  <span class="reply-uid" v-if="reply.author?.id">UID: {{ reply.author.id }}</span>
                </div>
              </div>
              <p class="reply-content">{{ reply.content }}</p>
            </div>
          </div>

          <!-- 回复输入框 -->
          <div class="reply-input" v-if="comment.showReplyInput">
            <el-input
              v-model="comment.replyText"
              placeholder="回复..."
              size="small"
              @keyup.enter="submitReply(comment)"
            >
              <template #append>
                <el-button 
                  size="small" 
                  type="primary"
                  @click="submitReply(comment)"
                  :disabled="!comment.replyText?.trim()"
                >
                  发送
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 空评论状态 -->
      <div v-else class="empty-comments">
        <el-empty description="暂无评论" :image-size="60" />
      </div>
      
      <!-- 添加评论表单 -->
      <div class="comment-form">
        <el-input
          v-model="newCommentText"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          resize="none"
          maxlength="500"
          show-word-limit
        />
        <div class="comment-actions">
          <el-button 
            type="primary" 
            @click="addComment" 
            :disabled="!newCommentText.trim()"
          >
            <el-icon><Promotion /></el-icon>
            发表评论
          </el-button>
        </div>
      </div>
    </div>

    <!-- 举报对话框 -->
    <el-dialog
      v-model="showReportDialog"
      title="举报用户"
      width="500px"
      align-center
    >
      <el-form
        ref="reportFormRef"
        :model="reportForm"
        :rules="reportRules"
        label-width="80px"
      >
        <el-form-item label="用户UID" prop="targetUid">
          <el-input 
            v-model="reportForm.targetUid" 
            placeholder="被举报用户UID"
            disabled
          />
        </el-form-item>
        
        <el-form-item label="举报内容" prop="content">
          <el-input
            v-model="reportForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述举报原因..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="举报图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :file-list="reportForm.images"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :auto-upload="false"
            :limit="3"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传3张图片，每张不超过2MB</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showReportDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitReport"
            :loading="submittingReport"
          >
            提交举报
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Warning } from '@element-plus/icons-vue'

const props = defineProps({
  post: {
    type: Object,
    required: true,
    default: () => ({})  // 提供默认值
  },
  currentUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['close', 'like', 'dislike', 'add-comment', 'add-reply'])

// 响应式数据
const showComments = ref(false)
const newCommentText = ref('')

// 举报相关状态
const showReportDialog = ref(false)
const submittingReport = ref(false)
const reportFormRef = ref()

// 举报表单数据
const reportForm = reactive({
  targetUid: '',
  content: '',
  images: []
})

// 表单验证规则
const reportRules = {
  content: [
    { required: true, message: '请输入举报内容', trigger: 'blur' },
    { min: 10, message: '举报内容至少10个字符', trigger: 'blur' }
  ]
}

// 计算属性 - 添加安全检查
const isOwnPost = computed(() => {
  return props.post?.author?.id === props.currentUser?.id
})

// 判断是否是当前用户
const isCurrentUser = (userId) => {
  return userId === props.currentUser?.id
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  
  const now = new Date()
  const targetDate = new Date(date)
  const diff = now - targetDate
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return targetDate.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }
}

// 预览图片
const previewImage = (imageUrl) => {
  // 这里可以添加图片预览逻辑
  console.log('预览图片:', imageUrl)
}

// 处理点赞
const handleLike = () => {
  if (!props.post?.id) return
  emit('like', props.post.id)
}

// 处理点踩
const handleDislike = () => {
  if (!props.post?.id) return
  emit('dislike', props.post.id)
}

// 切换评论显示
const toggleComments = () => {
  showComments.value = !showComments.value
}

// 添加评论
const addComment = () => {
  if (!newCommentText.value.trim() || !props.post?.id) return
  
  emit('add-comment', {
    postId: props.post.id,
    content: newCommentText.value.trim(),
    author: props.currentUser
  })
  
  newCommentText.value = ''
}

// 处理回复
const handleReply = (comment) => {
  if (!comment) return
  
  // 初始化回复输入框
  if (!comment.replyText) {
    comment.replyText = ''
  }
  comment.showReplyInput = !comment.showReplyInput
}

// 提交回复
const submitReply = (comment) => {
  if (!comment?.replyText?.trim() || !props.post?.id || !comment.id) return
  
  emit('add-reply', {
    postId: props.post.id,
    commentId: comment.id,
    content: comment.replyText.trim(),
    author: props.currentUser
  })
  
  // 清空回复输入框并隐藏
  comment.replyText = ''
  comment.showReplyInput = false
}

// 举报处理
const handleReport = () => {
  if (!props.post?.author?.id) {
    ElMessage.error('用户信息不完整，无法举报')
    return
  }
  
  // 初始化表单数据
  reportForm.targetUid = props.post.author.id.toString()
  reportForm.content = ''
  reportForm.images = []
  
  showReportDialog.value = true
}

// 图片上传处理
const handleImageChange = (file) => {
  // 检查文件大小
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  
  // 检查文件类型
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 添加到图片列表
  reportForm.images.push({
    name: file.name,
    url: URL.createObjectURL(file.raw),
    raw: file.raw
  })
}

// 图片移除处理
const handleImageRemove = (file) => {
  const index = reportForm.images.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    reportForm.images.splice(index, 1)
  }
}

// 提交举报
const submitReport = async () => {
  if (!reportFormRef.value) return
  
  try {
    // 验证表单
    await reportFormRef.value.validate()
    
    submittingReport.value = true
    
    // 构建表单数据
    const formData = new FormData()
    formData.append('targetUid', reportForm.targetUid)
    formData.append('content', reportForm.content)
    formData.append('reporterUid', props.currentUser?.id || '')
    formData.append('reporterName', props.currentUser?.name || '')
    formData.append('postId', props.post?.id || '')
    
    // 添加图片文件
    reportForm.images.forEach((image, index) => {
      formData.append(`images`, image.raw)
    })
    
    // 模拟提交到后端API
    console.log('提交举报数据:', {
      targetUid: reportForm.targetUid,
      content: reportForm.content,
      images: reportForm.images.length,
      reporterUid: props.currentUser?.id,
      postId: props.post?.id
    })
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('举报提交成功，管理员将在24小时内处理')
    showReportDialog.value = false
    
    // 重置表单
    reportFormRef.value.resetFields()
    reportForm.images = []
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submittingReport.value = false
  }
}
</script>

<style scoped>
.post-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  flex: 1;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 1rem;
}

.user-uid {
  font-size: 0.75rem;
  color: #6b7280;
}

.post-time {
  font-size: 0.875rem;
  color: #6b7280;
  white-space: nowrap;
}

.post-content {
  margin-bottom: 20px;
}

.post-text {
  color: #374151;
  line-height: 1.6;
  margin-bottom: 16px;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-keywords {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.keyword-tag {
  background: linear-gradient(135deg, #fef7ed, #fed7aa);
  border-color: #fdba74;
  color: #9a3412;
  font-weight: 500;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 8px;
}

.post-image {
  height: 120px;
  border-radius: 8px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.post-image:hover {
  transform: scale(1.02);
}

.post-image:hover .image-overlay {
  opacity: 1;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.post-stats-detail {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 0.75rem;
  color: #6b7280;
}

.stat-value {
  font-weight: 600;
  color: #1f2937;
}

.post-actions {
  margin-bottom: 20px;
}

.action-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.action-group .el-button.active {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.comments-section {
  border-top: 1px solid #e5e7eb;
  padding-top: 20px;
}

.comments-list {
  margin-bottom: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #f1f5f9;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 8px;
  justify-content: space-between;
}

.comment-author {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
}

.author-name {
  font-weight: 500;
  color: #374151;
  font-size: 0.875rem;
}

.comment-time,
.reply-time {
  font-size: 0.75rem;
  color: #9ca3af;
}

.comment-uid,
.reply-uid {
  font-size: 0.75rem;
  color: #9ca3af;
}

.comment-content {
  color: #4b5563;
  font-size: 0.875rem;
  line-height: 1.5;
  margin-bottom: 12px;
  padding-left: 44px;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

/* 回复列表 */
.replies-list {
  margin-left: 44px;
  margin-top: 12px;
  border-left: 2px solid #e5e7eb;
  padding-left: 16px;
}

.reply-item {
  padding: 12px 0;
  border-bottom: 1px solid #f8fafc;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-header {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 4px;
}

.reply-content {
  color: #6b7280;
  font-size: 0.875rem;
  line-height: 1.4;
  padding-left: 36px;
}

/* 回复输入框 */
.reply-input {
  margin-top: 12px;
  padding-left: 44px;
}

.empty-comments {
  margin-bottom: 20px;
}

.comment-form {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e5e7eb;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 举报相关样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .action-group {
    flex-direction: column;
  }
  
  .comment-content {
    padding-left: 0;
  }
  
  .reply-input {
    padding-left: 0;
  }
  
  .replies-list {
    margin-left: 20px;
  }
  
  .comment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>